<template>
  <div class="sensor-sort" @mousedown.stop @dragover.stop.prevent @drop.stop.prevent>
    <el-text class="mx-1" type="danger" size="small">
      所选择的模版中一组包含
      <span style="color: #67c23a; font-size: 16px; font-weight: bold">{{ colData.length }}</span>
      个传感器，以下一排为一组，排数不限
    </el-text>

    <div class="sensor-sort-grid">
      <div class="grid-header" :style="gridStyle">
        <div class="grid-header-item first-col">序号</div>
        <div class="grid-header-item" v-for="(item, index) of colData" :key="index">
          {{ item }}
        </div>
      </div>
      <div class="draggable-grid" :style="gridStyle">
        <div class="grid-item first-col">
          <div class="sensor-item" v-for="rowIndex in rowIndexArray" :key="rowIndex">
            {{ rowIndex + 1 }}
          </div>
        </div>
        <div class="grid-item" v-for="[key, value] in Object.entries(modelValue)" :key="key">
          <draggable
            v-model="value.list"
            :group="value.type"
            style="min-height: 100%"
            item-key="element"
            :disabled="disabled"
          >
            <template #item="{ element }">
              <div class="sensor-item"> {{ element }}</div>
            </template>
          </draggable>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import draggable from 'vuedraggable'
import _ from 'lodash'
const props = defineProps({
  modelValue: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const colData = computed(() => Object.values(props.modelValue).map((column) => column.type))

const rowIndexArray = computed(() => {
  const maxLength = Math.max(
    ...Object.values(props.modelValue).map((col) => col.list.length),
    0 // 防止空数据时报错
  )

  return Array.from({ length: maxLength }, (_, i) => i)
})

// 计算样式
const gridStyle = computed(() => ({
  display: 'grid',
  gridTemplateColumns: `32px repeat(${colData.value.length}, minmax(80px, 1fr))`,
  gap: '10px',
  minWidth: '100%'
}))
</script>
<style lang="scss" scoped>
.sensor-sort {
  overflow-x: auto;
  border: 1px solid #e8edff;
  padding: 10px;
  border-radius: 4px;

  .sensor-sort-grid {
    margin-top: 10px;
  }

  .grid-header {
    background-color: #eff2fc;
    padding: 5px 10px;

    .grid-header-item {
      font-weight: bold;

      &.first-col {
        min-width: 0;
      }
    }
  }

  .draggable-grid {
    padding: 10px;
  }

  .first-col {
    .sensor-item {
      border: 0;
    }
  }
  .sensor-item {
    border: 1px solid #dfdfdf;
    background: #fff;
    padding: 4px 0;
    margin-bottom: 10px;
    cursor: pointer;
  }
}

.test {
  width: 300px;
  overflow: auto;

  .grid-h {
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(100, minmax(100px, 1fr));
    min-width: 100%;
  }
}
</style>
